package com.freelancer.musicinstruction.services.impl.youtube;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

import com.freelancer.musicinstruction.beans.interfaces.MusicInstruction;
import com.freelancer.musicinstruction.services.exceptions.SaxParseCompleteException;
import com.freelancer.musicinstruction.services.interfaces.ISearchServices;

public class YoutubeSearchService implements ISearchServices {
	
	private static String TAG = YoutubeSearchService.class.getSimpleName();
	
	private Integer resultLimit;
	
	private YoutubeFeedHandler feedHandler;
	
	public YoutubeSearchService(  Integer resultLimit ){
		this.resultLimit = resultLimit;
		this.feedHandler = new YoutubeFeedHandler( resultLimit );
	}
	
	
	@Override
	public List<MusicInstruction> search(String searchString){
		Log.d(TAG, "search called");
		XMLReader xr;
		
		try{
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			xr = sp.getXMLReader();
			xr.setContentHandler( feedHandler );
			
			URL url = new URL( searchString );
			InputStream is = url.openStream();
			
			Long startTime = System.nanoTime();
			
			xr.parse( new InputSource ( is ) );
			
			Long endTime = System.nanoTime();
			
			Log.d(TAG, "Parse Time = "+ (endTime - startTime)/1000000000.0 + " seconds");
			
			is.close();
		}
		catch (IOException e) {
			e.printStackTrace();
			return null;
		} 
		catch (ParserConfigurationException e) {
			e.printStackTrace();
			return null;
		} 
		catch (SAXException e) {
			Log.d(TAG, e.getMessage());
			
			ArrayList<MusicInstruction>  vids;
			
			if( ((YoutubeFeedHandler) feedHandler).getVideos() != null && feedHandler.getVideos().size() != 0){
				vids = (ArrayList<MusicInstruction>) ((YoutubeFeedHandler) feedHandler).getVideos();
				Log.d( TAG, "Number of Videos: "+ vids.size());
				return vids;
			}
			else{
				return null;
			}
		}
		
		Log.d(TAG, "Search Over");
		return null;
	}

	public YoutubeFeedHandler getFeedHandler() {
		return feedHandler;
	}


	@Override
	public String getQueryString() {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	public void setQueryString(String queryString) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public String getUrl() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setUrl(String url) {
		// TODO Auto-generated method stub
		
	}

}
